<?php
//
// +--------------------------------------+
// |PHP version 5.6
// +--------------------------------------+
// |短信验证码api
// +--------------------------------------+
// |2018-01-17
// +--------------------------------------+
// |潘龙兵
// +--------------------------------------+
// |知果汇短信接口管理
// +--------------------------------------+
//
namespace app\api\controller;
use think\View;
use think\Controller;
use think\Db;
use app\data\Data;
use app\api\model\Common;
use think\Config;
use app\api\model\Client;
use phpmailer\phpmailer;  
class Message extends Index {
    static $id = 'opticsipr';
    static $pwd = 'Lanbroad202';
    static $url = 'http://service.winic.org:8009/sys_port/gateway/index.asp?';
    /*
     * @知果汇
     * @短信验证码发送
     * @2018-01-17
     * @潘龙兵
     * $status为1时注册，2为忘记密码,3为登录
    */
    public function sms(){
        if(empty($_GET['phone']) || empty($_GET['status'])){
            $this->_jsonp("1004","参数错误",null);
        }
        $status = (int)$_GET['status'];
        $phone  = (string)$_GET['phone'];
        // echo $phone;exit;
        $where['phone'] = $phone;
        $zgh_user = new Data('user');
        if($status == 1){//注册
            $count = $zgh_user->count($where);
            if($count != 0){
                $this->_jsonp("1002","手机已注册",null);
            }   
        }else if($status == 2){//忘记密码
            $count = $zgh_user->count($where);
            if($count == 0){
                $this->_jsonp("1003","手机未注册",null);
            }
        }else if($status == 3){
            $count = $zgh_user->count($where);
            if($count != 0){
                $this->_jsonp("1002","手机已注册",null);
            }
        }
        $c_sms = Config::get('think_sms');//获取配置文件中短信接口配置
        $action = $c_sms['sms_url'];
        // dump($action);exit;
        $code = $this -> GetRandInt();
        $Client = new Client;
        $form = $Client -> get_ip_from();//获取用户出口ip
        $info = array(
            "message" =>$phone, 
            "code" => $code,
            "time" => time(),
            "ip" => $form['ip'],
            "status" =>1,
            "is_status" => 0
            );
        $where = array(
            "message" => $info['message'],
            "ip" =>$info['ip'],
            "time" => array("between",array(time()-60,time())),
            "status" =>$info['status']
            );
        $zgh_sms_code = new Data('sms_code');
        $count = $zgh_sms_code->count($where);
        // dump($count);exit;
        if($count > 0){
            $this->_jsonp("1003","发送频繁",null);
        }
         //dump($info);exit;
        $info = $zgh_sms_code -> _insert($info);
        if(!$info){
            $this->_jsonp("1002","数据库异常",null);
        }
        $info = $this->sms_news($phone,$code);
        //dump($info);exit;
        if($info == '000'){
            $info = json_decode($info,true);
            if($info['code'] == 0){
                $this->_jsonp("200","发送成功",null);
            }else{
                $this->_jsonp("1001","网络错误",null);
            }
        }else{
            $this->_jsonp("1000","网络错误",null);
        }
    }


    /*
     * @知果汇
     * @配置短信参数
     * @2018-02-05
     * @潘龙兵
     * @ $url 地址
     *      $rdata 传输数据
     *      $id 账号
     *      $pwd 密码
     *      $to 短信接收手机号
     */
    public function sms_news($Mobile,$rand){
        $data = "id=%s&pwd=%s&to=%s&content=%s&time=";
        $url = self::$url;
        $id = self::$id;
        $pwd = self::$pwd;
        $to = $Mobile; 
        $Content = "您好，您的验证码是".$rand."。仅用于知果汇注册或找回密码及快捷登录手机验证。请不要把验证码泄露给他热人。如非本人操作，可不用理会！";
        $content = iconv("utf-8","gb2312",$Content);
        $rdata = sprintf($data, $id, $pwd, $to, $content);
        $result = self::sms_curl($url,$rdata);
        //$result = "-04/Send:1/Consumption:.05/Tmoney:999.25/sid:0612162821058762";
        $result = explode("/",$result);
        return $result[0];
   }


   /*
     * @知果汇
     * @发起 server 请求
     * @2018-02-05
     * @潘龙兵
     * @ $url 地址
     *      $rdata 传输数据
     */
   private function sms_curl($url,$rdata){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST,1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$rdata);
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
   }
    
    /*
     * @知果汇
     * @短信验证码验证
     * @2018-01-18
     * @潘龙兵
     */
    public function check_sms(){ 
        if(empty($_GET['message']) || empty($_GET['code'])){
            $this->_jsonp("1003","参数错误",null);
        }
        $message = (string)$_GET['message'];
        $code = $_GET['code'];
        $where = array(
           "message" =>$message,
           "code" => $code,
           "status" => 1,
           );
        $zgh_sms_code = new Data('sms_code');
        // dump($zgh_sms_code);exit; 
        $field = 'id,time,code,is_status';
        $info = $zgh_sms_code->_find($where,$field);
        if (!$info) {
            $this->_jsonp("1000","验证码错误",null);
        }
        // $_time = time() - 180;
        /*$_time = time() - 100000;//测试，上线时删除此条
        if($_time > $info['time'] || $info['is_status'] == 1){
           $this->_jsonp("1001","验证码失效",null);
       }*/
       // M("sms_code") -> startTrans();
       $data['is_status'] = 1;
       $u_where['id'] = $info['id'];
       // $_info = $zgh_sms_code->_update($u_where,$field);
       // $_info = M("sms_code") ->where(array("id"=>$info['id'])) -> save(array("is_status" => 1));
       $_info = 1; //测试，上线时删除此条，并去掉上一条注释
       if(!$_info){
           $this->_jsonp("1000","数据库异常",null);
       }
       if($code == $info['code']){
            if(isset($_GET['login'])){
                $where_login['phone'] = $message;
                $where_login['status'] = 1;
                $zgh_user = new Data('user');
                $field_login = 'uid,username';
                $result = $zgh_user->_find($where_login,$field_login);
                $this->_jsonp("200","登录成功",$result);
            }   
           // Cache::set('name',$value,1800); // 设置缓存180s
           $this->_jsonp("200","验证通过",null);
       }else{
           $this->_jsonp("1000","验证失败",null);
       }
   }

    /*
    * @知果汇
     * @邮箱验证码发送
     * @2018-01-18
     * @潘龙兵
    * @$to：接收邮件者邮箱
    *  $name：接收邮件者名称
    *  $subject：邮件主题 
    *  $body：邮件内容
    *  $attachment：附件列表
    *  $config：读取配置文件
    * @return boolean 
    */    
    public function send_email($to,$subject = '',$body = ''){
        $mail = new PHPMailer(); //PHPMailer对象
        $c_email = Config::get('think_email');//获取配置文件中短信接口配置
        $mail->CharSet    = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
        $mail->IsSMTP();  // 设定使用SMTP服务
        $mail->SMTPDebug  = 0;                     // 关闭SMTP调试功能
                                                   // 1 = errors and messages
                                                   // 2 = messages only
        $mail->SMTPAuth   = true;                  // 启用 SMTP 验证功能
        $mail->SMTPSecure = 'ssl';                 // 使用安全协议
        $mail->Host       = $c_email['smtp_host'];  // SMTP 服务器
        $mail->Port       = $c_email['smtp_port'];  // SMTP服务器的端口号
        $mail->Username   = $c_email['smtp_user'];  // SMTP服务器用户名
        $mail->Password   = $c_email['smtp_pass'];  // SMTP服务器密码
        $mail->SetFrom($c_email['form_email'], $c_email['form_name']);
        $replyEmail       = $c_email['reply_email']?$c_email['reply_email']:$c_email['reply_email'];
        $replyName        = $c_email['reply_name']?$c_email['reply_name']:$c_email['reply_name'];
        $mail->AddReplyTo($replyEmail, $replyName);
        $mail->Subject    = $subject; //邮件主题 
        $mail->MsgHTML($body);        //邮件内容
        $mail->AddAddress($to);       //收件方邮箱地址
        $send = $mail->Send();
        if(!$send) $this->_jsonp("1000","发送失败",null);
        // if(!$send) $this->error('发送失败：'.$mail->ErrorInfo);
    }


    /*
    * @知果汇
    * @验证邮箱，发送邮件
    * @2018-01-22
    * @潘龙兵
    * @$verify：实例化验证码
    *  $email：post得到的邮箱
    *  $key：激活的密钥
    *  $subject：邮件主题 
    *  $body：邮件内容
    *  $send_email：发送邮件
    *  $status:1(注册)；2(忘记密码)
    */ 
    public function email(){ 
        if(empty($_GET['email']) || empty($_GET['status'])){
            $this->_jsonp("1003","参数错误",null);
        }
        $email  = trim(input('get.email'));
        $status  = trim(input('get.status'));
        $where['email'] = $email;
        $zgh_user = new Data('user');
        $result = $zgh_user->_find($where);
        if($status == 1){
            if(isset($result)) $this->_jsonp('1000',"该邮箱已经注册",null);
            $name = '注册';
        }else if($status == 2){
            if(!isset($result)) $this->_jsonp('1000',"该邮箱还未注册",null);
            $name = '忘记密码';
        }else{
            if(isset($result)) $this->_jsonp('1000',"该邮箱已经注册",null);
            $name = '绑定账号';
        }
        
        $key = $this->GetRandInt();
        $subject = '知果汇用户'.$name; 
        $body  = '<p>尊敬的用户:</p>';   
        $body .= '<p>您的验证码为:'.$key.'，十分钟内有效。</p>';
        $body .= '<p>知果汇</p>';
        $send_email = $this->send_email($email,$subject,$body);
        // $this->email_common($email,$key);
        $Client = new Client;
        $form = $Client -> get_ip_from();//获取用户出口ip
        $info = array(
            "message" =>$email,
            "code" => $key,
            "time" => time(),
            "ip" => $form['ip'],
            "status" =>1,
            "is_status" => 0
            );
        $where = array(
            "message" => $info['message'],
            "ip" =>$info['ip'],
            "time" => array("between",array(time()-60,time())),
            "status" =>$info['status']
            );
        $zgh_sms_code = new Data('sms_code');
        $count = $zgh_sms_code->count($where);
        // dump($count);exit;
        if($count > 0){
            $this->_jsonp("1003","发送频繁",null);
        }
        // dump($info);exit;
        $info = $zgh_sms_code -> _insert($info);
        if(!$info){
            $this->_jsonp("1002","数据库异常",null);
        }
        $this -> _jsonp('200','发送成功',null);
        
    }


    /*
     * @知果汇
     * @ip地址获取
     * @2018-01-18
     * @潘龙兵
     */
    public function get_client_ip($type = 0) {
        $type =  $type ? 1 : 0;
        static $ip  =   NULL;
        if ($ip !== NULL) return $ip[$type];
        if($_SERVER['HTTP_X_REAL_IP']){//nginx 代理模式下，获取客户端真实IP
            $ip=$_SERVER['HTTP_X_REAL_IP'];
        }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {//客户端的ip
            $ip     =   $_SERVER['HTTP_CLIENT_IP'];
        }elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {//浏览当前页面的用户计算机的网关
            $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos    =   array_search('unknown',$arr);
            if(false !== $pos) unset($arr[$pos]);
            $ip     =   trim($arr[0]);
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip     =   $_SERVER['REMOTE_ADDR'];//浏览当前页面的用户计算机的ip地址
        }else{
            $ip=$_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u",ip2long($ip));
        $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }


    /*
     * @知果汇
     * @生成随机数
     * @2018-01-18
     * @潘龙兵
     * @$len: 随机数长度 默认4位
     * @$chars: 随机数数组
     * @$charsLen: 随机数数组长度
     * @$output: 输出数据
     */
    public function GetRandInt($len=6) {
        $chars = array(
               "0", "1", "2","3", "4", "5", "6", "7", "8", "9"
        );
        $charsLen = count($chars) - 1;
        shuffle($chars);
        $output = "";
        for ($i=0; $i<$len; $i++)
        {
            $output .= $chars[mt_rand(0, $charsLen)];
        }
        return $output;
    }


    /*
     * @知果汇
     * @判断数据是否为json
     * @2018-01-29
     * @潘龙兵
     */
    public function is_json($str) {
         return is_array(json_decode($str,true));
    }


}